/***************************************************************************
创建者：　华磊
 开始时间：               : 2020.1１.０1
 copyright            : (C) 深圳市华友高科有限公司
 修改说明：（每次有修改就添加一条，带有 修改人，修改时间，修改描述）

 ***************************************************************************
 *   程序运行视窗测试用代理类
*                                                                         *
 ***************************************************************************/
#include "../ProgramLanguageTranslate/programlanguagetranslate.h"
#include "rundelegate.h"
#include <QtCore>
#include "../RunView/runview.h"
#include <QMessageBox>
#include <QDebug>
#include "hmicommondefine.h"
#include "instructionEnum.h"
#include "../CommunicateDelegate/communicatenormaldelegate.h"

#define D_ROBOT_PICTURE_DIRECTORY "/agvwork/AgvFundation/fundation/data/robotImage/"

FileData fileData;

RunDelegate::RunDelegate(CommunicateNormalDelegate *communicateNormalIn, RunView *runViewIn,
                         GlobalData *globalDataIn, GlobalData *ioDataIn, MoveOperation *moveOperationIn,
                         ProgramLanguageTranslate *programLanguageTranslateIn, QObject *parent) : QObject(parent)
{
    communicateNormal=communicateNormalIn;
    runView=runViewIn;
    globalData = globalDataIn;
    ioData = ioDataIn;
    moveOperation=moveOperationIn;
    programLanguageTranslate=programLanguageTranslateIn;

    currentPointNumber = 0;//点编号,0为没有
    editLanguage = ENUM_LAN_ENGLISH;//默认
    initConnect();                     //初始化connenct
}

void RunDelegate::initConnect()
{
    connect(runView, SIGNAL(clearCurrentProductivitySignal()), this, SLOT(clearCurrentProductivitySlot()));
    connect(runView, SIGNAL(clearAccumulateProductivitySignal()), this, SLOT(clearAccumulateProductivitySlot()));
    connect(runView, SIGNAL(forcePutDownMaterialSignal()), this, SLOT(forcePutDownMaterialSlot()));
    connect(runView, SIGNAL(forceFetchMaterialSignal()), this, SLOT(forceFetchMaterialSlot()));

    connect(runView, SIGNAL(setCurrentSelectRow()),this,SLOT(setCurrentSelectRowSlot()));
    //connect(runView, SIGNAL(setCurrentSelectTab()),this,SLOT(setCurrentSelectTabSlot()));
    connect(runView->setLineDialog, SIGNAL(setRunStartRow(int)),this,SLOT(setStartRunRowSlot(int)));
}

RunDelegate::~RunDelegate()
{

}

void RunDelegate::forcePutDownMaterialSlot()
{
    //qDebug("forcePutDownMaterial");
}

void RunDelegate::forceFetchMaterialSlot()
{
    //qDebug("forceFetchMaterial");
}

void RunDelegate::setCurrentSelectRowSlot()
{
    //qDebug()<<"setCurrentSelectRowSlot = "<<runView->currentSelectRow;//文件 程序下标

    int row = runView->currentSelectRow;

    if(row >= 0 && row < fileData.cmdStrList.size())
    {
        QString tmpCurrent = fileData.cmdStrList[row];

        //判断有无P[]
        QString pattern("(.*)\\s+(P|PR)\\[(R\\[\\d+\\]|\\d+)\\]\\s*(.*)");
        QRegExp rx(pattern);
        int pos = tmpCurrent.indexOf(rx);
        if ( pos >= 0 )
        {
            if("P" == rx.cap(2))//P
            {
                currentPointType = 0;
            }
            else//PR
            {
                currentPointType = 1;
            }

            //currentPointNumber = rx.cap(3).toInt();//目前支持普通数值
            currentPointNumber = getRrgToIndex(rx.cap(3));
        }
        else
        {
            //qDebug() << "point number :0";
            currentPointNumber = 0;
        }
    }

    //qDebug()<<"currentPointNumber ** = "<<currentPointNumber;
}

int RunDelegate::getRrgToIndex(QString arg1)
{
    //qDebug()<<"arg1 = "<<arg1;
    std::vector<double > registerOut;
    ioData->getLocalRegister(registerOut);
    int index = 0;
    //QString patternRR = "^\\s*R\\[R\\[(\\d+)\\]\\]\\s*$";
    QString patternR = "^\\s*R\\[(\\d+)\\]\\s*$";
    QString patternC = "^\\s*(\\d+)\\s*$";
    //QRegExp rxRR(patternRR);
    QRegExp rxR(patternR);
    QRegExp rxC(patternC);

    int posC = arg1.indexOf(rxC);
    int posR = arg1.indexOf(rxR);
    //int posRR = arg1.indexOf(rxRR);

    //if(posC >= 0 || posR >= 0 || posRR >= 0)
    if(posC >= 0 || posR >= 0)
    {
        if(posC >= 0)
        {
            index = rxC.cap(1).toInt();
            return index;
        }
        if(ioData)
        {
//            ioData->lock();
            if(posR >= 0)
            {
                index = rxR.cap(1).toInt();
                if(index>0 && index<=registerOut.size())
                {
                    index = registerOut[index - 1];
//                    ioData->unlock();
                    return index;
                }
                else
                {
//                    ioData->unlock();
                    return 0;
                }
            }
//            if(posRR >= 0)
//            {
//                index = rxRR.cap(1).toInt();
//                if(index>0 && index<=ioData->localRegister.size())
//                {
//                    index = ioData->localRegister[index - 1];
//                    if(index>0 && index<=ioData->localRegister.size() )
//                    {
//                        index = ioData->localRegister[index - 1];
//                        ioData->unlock();
//                        return index;
//                    }
//                    else
//                    {
//                        ioData->unlock();
//                        return 0;
//                    }
//                }
//            }
        }
    }
    else
    {
//        ioData->unlock();
        return -10;
    }

//    ioData->unlock();
    return -10;
}

void RunDelegate::rightFunMoveToPointSlot(int type)
{
    if(!runView->isHidden())
    {
        if(currentPointNumber<=0)
        {
            qDebug()<<"currentPointNumber<=0";
            return;
        }

        //qDebug()<<"runView run type :"<< type;
        //qDebug() << "point type :" << currentPointType;
        //qDebug() << "point number :" << currentPointNumber;

        //moveToPointSlot(type,programView->currentLineIndex);
        std::vector<PointPro > pointregisterOut;
        ioData->getPointRegister(pointregisterOut);

//        if(globalData)
//        {
//            if(globalData->tryLock(TRYLOCKTIME))
//            {
                if(globalData->globalHandState >= EM_CONTROL_MODE_T2)
                {
//                    globalData->unlock();

                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前模式不可操作\n寸动请切换手动T1模式"));

                    return;
                }
                if(globalData->globalServoState != EM_MOTOR_STATUS_SERVO_ON)//使能开启
                {
//                    globalData->unlock();
                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("伺服使能没有启动,请启动"));
                    return;
                }
                else
                {
//                    globalData->unlock();
                }
//            }
//        }
//        else
//        {
//            return;
//        }

        //qDebug() << "point number :" << rx.cap(2);
        //int pointNumber = pointNumber;
        int arrayNumber = 0;//下标
        MoveParameter tmpMoveParameter;

        if(0 == currentPointType)//P
        {
            if(fileData.getPointProList.size() == 0)
            {
                emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前点没有载入点数据"));
                return;
            }

            //新判定 方法 支持动态
            if(currentPointNumber > fileData.getPointProList.size())
            {
                emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前点没有载入点数据"));
                return ;
            }
            else
            {
                arrayNumber = currentPointNumber-1;//该点存在,获取下标
            }


            tmpMoveParameter.moveType = type;//默认关节方式移动
            //tmpMoveParameter.targetPoint = fileData.getPointProList[pointNumber];

//            tmpMoveParameter.targetPoint.jointFlag = fileData.getPointProList[arrayNumber].jointFlag;
//            tmpMoveParameter.targetPoint.pointNum = fileData.getPointProList[arrayNumber].pointNum;
//            tmpMoveParameter.targetPoint.groupNum = fileData.getPointProList[arrayNumber].groupNum;
//            tmpMoveParameter.targetPoint.ufValue = fileData.getPointProList[arrayNumber].ufValue;
//            tmpMoveParameter.targetPoint.utValue = fileData.getPointProList[arrayNumber].utValue;
//            tmpMoveParameter.targetPoint.recordStatus = 0;
//            //多圈 目前空
//            tmpMoveParameter.targetPoint.configString = fileData.getPointProList[arrayNumber].configString;
//            //tmpMoveParameter.targetPoint.configInt = ;//int
//            for(int i = 0;i < fileData.getPointProList[arrayNumber].positionValue.size();i++)
//            {
//                tmpMoveParameter.targetPoint.positionValue.push_back(fileData.getPointProList[arrayNumber].positionValue[i]);//float
//            }
//            for(int i = 0;i < fileData.getPointProList[arrayNumber].extPositionValue.size();i++)
//            {
//                tmpMoveParameter.targetPoint.extPositionValue.push_back(fileData.getPointProList[arrayNumber].positionValue[i]);//float
//            }
            tmpMoveParameter.targetPoint = fileData.getPointProList[arrayNumber];

            tmpMoveParameter.pointType = 0;//普通点
        }
        else//PR
        {
            //新判定 方法 支持动态
//            ioData->lock();
            if(currentPointNumber > pointregisterOut.size())
            {
//                ioData->unlock();
                emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("不存在此PR点数据"));
                return ;
            }
            else
            {
                arrayNumber = currentPointNumber-1;//该点存在,获取下标
            }

            tmpMoveParameter.moveType = type;//默认关节方式移动
            tmpMoveParameter.targetPoint = pointregisterOut[arrayNumber];
            tmpMoveParameter.pointType = 0;//普通点

//            ioData->unlock();
        }

        //emit moveToPointSignal(tmpMoveParameter);
        moveOperation->startPointMove(tmpMoveParameter);
    }
}

void RunDelegate::rightFunMoveStopSlot()
{
    if(!runView->isHidden())
    {
        moveOperation->stopPointMove();
    }
}

void RunDelegate::setStartRunRowSlot(int line)
{
//    if(globalData->tryLock(TRYLOCKTIME))
//    {
        if(globalData->globalCurrentState == ENUM_COMMAND_RUN || globalData->globalCurrentState == ENUM_COMMAND_CEASE)
        {
//            globalData->unlock();

            runView->setLineDialog->hide();
            emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("程序非停止状态下禁止设置"));

            return;
        }

//        globalData->unlock();
//    }

    emit setProgramRunLineSignal(line);
}

void RunDelegate::clearCurrentProductivitySlot()
{
//    runView->currentProductivity = 0;
//    runView->updateViewShow();
    //qDebug("clearCurrentProductivity");
    emit clearCurrentProductivitySignal();
}

void RunDelegate::clearAccumulateProductivitySlot()
{
//    runView->accumulateProductivity = 0;
//    runView->updateViewShow();
    //qDebug("clearAccumulateProductivity");
    emit clearAccumulateProductivitySignal();
}

void RunDelegate::updateDataAndView()
{
    if(globalData)
    {
        CurrentRunFile currentRunFileOut;
        globalData->getCurrentRunFile(currentRunFileOut);
//        if(  globalData->tryLock() )
//        {
//            if(globalData->globalCurrentState != ENUM_COMMAND_RUN)
//            {
//                //qDebug()<<runView->cacheFileCode.size();
//                if(runView->cacheFileCode.size() > 0)
//                {
//                    qDebug()<<"clean the file map";
//                    runView->cacheFileCode.clear();
//                }
//            }

            //qDebug()<<"RunDelegate::updateDataAndView()";
            // 跟新当前产量丶累计产量丶效率数据
            runView->currentProductivity = globalData->currentProductivity;      //当前产量 globalData->currentProductivity
            runView->accumulateProductivity = globalData->accumulateProductivity;   //累计产量 globalData->accumulateProductivity
            runView->runEfficiency = globalData->workpieceRatio;            //效率

            //runView->robotPicture = QString(ROBOT_PIC_PATH)+"scara-600.png";
            //qDebug()<<QString::fromStdString(globalData->currentRobotPicAddress);
            // 更新程序运行界面显示的图片
            QString tmpDir=D_ROBOT_PICTURE_DIRECTORY;
            runView->robotPicture = tmpDir+QString::fromStdString(globalData->getCurrentRobotPictureAddress());

            // 更新运行文件数量
            int runFileCount = currentRunFileOut.runingFileName.size();

            // 更新界面现存数量
            int viewRunFileCount = runView->runProInfo.runingFileName.size();//界面现存 数量
            int line = 1;

            //qDebug()<<runFileCount<<"**"<<viewRunFileCount;
            if(runFileCount != viewRunFileCount)
            {
                //runView->currentSelectTab = 0;//选中的tab 归 0
                runView->runProInfo.runingFileName.clear();
                runView->runProInfo.runingFileLine.clear();
                runView->runProInfo.runingFileCode.clear();

                //qDebug()<<"!= __size runFileCount "<<runFileCount;
                //qDebug()<<"!= __size globalData f "<<globalData->currentRunFile.runingFileName.size();
                //for(int i = 0;i < runFileCount;i++)
                //if(globalData->currentRunFile.runingFileName.size() > 10)
                //{
                //    return ;//暂时处理,不知道有没有关系,对于runFileName 获得空数据,长度缺没问题的问题
                //}
                for(int i = 0;i < currentRunFileOut.runingFileName.size();i++)
                {
                    //程序名
                    std::string runFileName = currentRunFileOut.runingFileName[i];
                    QString tmpRunName = tr(runFileName.data());//qDebug()<<"tmpRunName "<<tmpRunName;
                    runView->runProInfo.runingFileName.append(tmpRunName);

                    //程序内容
                    QStringList tmp;
                    if(fileData.currentFileName == tmpRunName)
                    {   
                        tmp<<runView->cacheMainFileCode;
                        if(0 == tmp.size())
                        {
//                            qDebug()<<"the main file not in cache,now save:"<<tmpRunName;
                            if(globalData->editLanguage == ENUM_LAN_CHINESE)
                            {
                                //获取翻译后的, 英文翻译成中文
//                                runView->cacheMainFileCode = fileData.translateCmdList(ENUM_LAN_CHINESE,fileData.cmdStrList);
                                // 翻译成中文,英文保留
                                runView->cacheMainFileCode = programLanguageTranslate->translateProgramCmdList(ENUM_LAN_CHINESE, fileData.cmdStrList);
                            }
                            else//english
                            {
                                //直接获取
                                runView->cacheMainFileCode = fileData.cmdStrList;
                            }

                            tmp<<runView->cacheMainFileCode;
                        }
                    }
                    else
                    {
                        tmp<<runView->cacheFileCode[tmpRunName];//2017.05.11添加 缓存措施:减少读文件的操作
                        if(0 == tmp.size())
                        {
                            qDebug()<<"this file not in map,now save:"<<tmpRunName;
                            fileData.readProgramToCode(tmpRunName,tmp);
                            emit runningProgramFileChanged();
                            if(globalData->editLanguage == ENUM_LAN_CHINESE)//若是中文就翻译;不是就英文原文
                            {
//                                tmp = fileData.translateCmdList(ENUM_LAN_CHINESE,tmp);
                                tmp = programLanguageTranslate->translateProgramCmdList(ENUM_LAN_CHINESE,tmp);
                            }
                            runView->cacheFileCode.insert(tmpRunName,tmp);
                        }
                    }
                    runView->runProInfo.runingFileCode.append(tmp);

                    //程序当前行号
                    if(currentRunFileOut.runningFileLine[i]>0)
                    {
                        line = currentRunFileOut.runningFileLine[i];
                    }
                    else
                    {
                        line = 1;
                    }
                    runView->runProInfo.runingFileLine.append(line);
                }
                runView->runFileUpdateFlag = true;
            }
            else                                    //数据长度没有变化
            {
                //qDebug()<<"== __size runFileCount "<<runFileCount;
                //qDebug()<<"== __size globalData f "<<globalData->currentRunFile.runingFileName.size();
                for(int i = 0;i < currentRunFileOut.runingFileName.size();i++)
                {
                    //程序名
                    std::string runFileName = currentRunFileOut.runingFileName[i];
                    QString tmpRunName = tr(runFileName.data());
                    if(runView->runProInfo.runingFileName[i] != tmpRunName )
                    {
                        runView->runProInfo.runingFileName.replace(i,tmpRunName);

                        //程序内容
                        QStringList tmp;
                        if(fileData.currentFileName == tmpRunName)
                        {
                            tmp<<runView->cacheMainFileCode;
                            if(0 == tmp.size())
                            {
//                                qDebug()<<"the main file not in cache,now save:"<<tmpRunName;
                                if(globalData->editLanguage == ENUM_LAN_CHINESE)
                                {
                                    //获取翻译后的
//                                    runView->cacheMainFileCode = fileData.translateCmdList(ENUM_LAN_CHINESE,fileData.cmdStrList);
                                    runView->cacheMainFileCode = programLanguageTranslate->translateProgramCmdList(ENUM_LAN_CHINESE,fileData.cmdStrList);
                                }
                                else//english
                                {
                                    //直接获取
                                    runView->cacheMainFileCode = fileData.cmdStrList;
                                }

                                tmp<<runView->cacheMainFileCode;
                            }
                        }
                        else
                        {
                            tmp<<runView->cacheFileCode[tmpRunName];//2017.05.11添加 缓存措施:减少读文件的操作
                            if(0 == tmp.size())
                            {
                                qDebug()<<"this file not in map,now save:"<<tmpRunName;
                                fileData.readProgramToCode(tmpRunName,tmp);
                                emit runningProgramFileChanged();
                                if(globalData->editLanguage == ENUM_LAN_CHINESE)//若是中文就翻译;不是就英文原文
                                {
//                                    tmp = fileData.translateCmdList(ENUM_LAN_CHINESE,tmp);
                                    tmp = programLanguageTranslate->translateProgramCmdList(ENUM_LAN_CHINESE,tmp);
                                }
                                runView->cacheFileCode.insert(tmpRunName,tmp);
                            }
                        }
                        runView->runProInfo.runingFileCode.replace(i,tmp);

                        runView->runFileUpdateFlag = true;
                    }

                    //程序当前行号
                    line = currentRunFileOut.runningFileLine[i];
                    if(runView->runProInfo.runingFileLine[i] != line)
                    {
                        runView->runProInfo.runingFileLine.replace(i,line);
                        runView->runFileUpdateFlag = true;
                    }
                }

                //qDebug()<< "else name :" <<runView->runProInfo.runingFileName.size();
                //qDebug()<< "else line :" <<runView->runProInfo.runingFileLine.size();
                //qDebug()<< "else code :" <<runView->runProInfo.runingFileCode.size();
            }
            //qDebug()<< " name :" <<runView->runProInfo.runingFileName;
            //qDebug()<< " line :" <<runView->runProInfo.runingFileLine;
            //qDebug()<< " code :" <<runView->runProInfo.runingFileCode;

            //关联文件
            int relatedFileCount = currentRunFileOut.relatedFileName.size();//更新数据 数量
            int viewRelatedFileCount = runView->runProInfo.runRelatedFileName.size();//界面现存 数量

            if(relatedFileCount != viewRelatedFileCount)
            {
                runView->runProInfo.runRelatedFileName.clear();

                for(int i = 0;i <relatedFileCount;i++)
                {
                    std::string relatedFileName = currentRunFileOut.relatedFileName[i];
                    runView->runProInfo.runRelatedFileName.append(tr(relatedFileName.data()));
                }
                runView->runFileUpdateFlag = true;
            }
            else
            {
                for(int i = 0;i <relatedFileCount;i++)
                {
                    std::string relatedFileName = currentRunFileOut.relatedFileName[i];
                    QString tmpRelated = tr(relatedFileName.data());
                    if(runView->runProInfo.runRelatedFileName[i] != tmpRelated)
                    {
                        runView->runProInfo.runRelatedFileName.replace(i,tmpRelated);
                        runView->runFileUpdateFlag = true;
                    }
                }
            }


//            globalData->unlock();
//            //qDebug()<<"RunDelegate::updateDataAndView() unlock()";
//        }
    }
    //界面更新
    runView->updateViewShow();
    monitorRobotPictureChange();

    //若文件有更新编辑 重新载入(communicate中updateUserProgramFile会设值控制)
    if(fileData.cmdStrWriteSuccess)
    {
        runView->runProInfo.runingFileName.clear();
        runView->runProInfo.runingFileLine.clear();
        runView->runProInfo.runingFileCode.clear();

        runView->tmpFileSize = 0;

        //补充:如果更新了,翻译和缓存 也要重新开始
        runView->cacheMainFileCode.clear();
//        qDebug()<<"clean the main file cache";

        runView->cacheFileCode.clear();
//        qDebug()<<"clean the file map";

        fileData.cmdStrWriteSuccess = false;
    }
}

void RunDelegate::monitorRobotPictureChange()
{
    if(runView->tmpPicAddress != runView->robotPicture)
    {
        std::string imageStrOut;
        communicateNormal->getImageStringFormImagePath(runView->robotPicture.toStdString(),imageStrOut);
        runView->updateRobotPictureShow(imageStrOut);
        runView->tmpPicAddress = runView->robotPicture;
    }

}

void RunDelegate::changeEditLanguageSlot(int language)
{
    if( editLanguage != language)
    {
        editLanguage = language;

        //所有重置
        runView->runProInfo.runingFileName.clear();
        runView->runProInfo.runingFileLine.clear();
        runView->runProInfo.runingFileCode.clear();

        runView->tmpFileSize = 0;

        //补充:如果更新了,翻译和缓存 也要重新开始
        runView->cacheMainFileCode.clear();
        qDebug()<<"clean the main file cache";

        runView->cacheFileCode.clear();
        qDebug()<<"clean the file map";
    }
}

bool RunDelegate::openFileAndCreateList(QString fileName)
{
    return true;
}

void RunDelegate::changeLanguageSlot(int language)
{
    if(1 == language)
    {
        translator.load("/agvwork/AgvHmi/baseBag/hmiProject/language/runViewDelEnglishLan.qm");
        qApp->installTranslator(&translator);
    }
    else
    {
        qApp->removeTranslator(&translator);
    }
    runView->changeLanguage(language);
}

